package com.supcalls.collections;

import java.util.*;
import java.util.concurrent.*;

public class ThreadSafeCollectionDemo {

    // 使用 synchronizedList 实现线程安全的 List
    public static void synchronizedListExample() {
        List<Integer> list = Collections.synchronizedList(new ArrayList<>());

        // 创建多个线程操作该集合
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("SynchronizedList size: " + list.size());
    }

    // 使用 CopyOnWriteArrayList 实现线程安全的 List
    public static void copyOnWriteArrayListExample() {
        List<Integer> list = new CopyOnWriteArrayList<>();

        // 创建多个线程操作该集合
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i);
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("CopyOnWriteArrayList size: " + list.size());
    }

    public static void main(String[] args) {
        System.out.println("SynchronizedList Example:");
        synchronizedListExample();

        System.out.println("\nCopyOnWriteArrayList Example:");
        copyOnWriteArrayListExample();
    }
}

